/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sita.bike.ui.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.sita.bike.R;
import com.sita.friend.event.AcceptFriendEvent;
import com.sita.friend.event.AddFriendEvent;
import com.sita.friend.event.ConversationMessageHasReadEvent;
import com.sita.friend.event.ReceiveMessageEvent;
import com.sita.friend.ui.fragment.FriendFragment;
import com.sita.friend.utils.MessageUtils;
import com.sita.tboard.ui.fragment.DiscoveryFragment;
import com.sita.tboard.ui.fragment.MapSpeedDashboardFragment;
import com.sita.tboard.ui.fragment.MineFragment;
import com.sita.tboard.ui.view.ImgTextBtn;

import de.greenrobot.event.EventBus;

public class MainFragment extends Fragment {

    protected static final String TAG = MainFragment.class.getSimpleName();
    public static final int TAB_MAP = 0;
    protected static final int TAB_DISCOVER = 1;
    protected static final int TAB_FRIEND = 2;
//    protected static final int TAB_MEDIA = 3;
    protected static final int TAB_ME = 3;
    protected static final int TAB_COUNT = TAB_ME + 1;
    private static MainFragment instance;
    private ImgTextBtn[] mTabs;
    private MapSpeedDashboardFragment mMapFragment;
    private DiscoveryFragment mDiscoveryFragment;
    private FriendFragment mFriendFragment;
//    private FragmentRecommends mMediaFragment;
    private MineFragment mMineFragment;
    private Fragment mCurrentFragment = null;
    private int currentTabIndex = -1;
    private TextView unread_msg_number;

    public static MainFragment getInstance() {
        instance = new MainFragment();
        return instance;
    }

    public Fragment getMapFragment() {
        return mMapFragment;
    }

    public void showTrends(String resourceId) {
        DiscoveryFragment discoveryFragment = (DiscoveryFragment) selectFragment(TAB_DISCOVER);
        selectTab(TAB_DISCOVER);
        discoveryFragment.showTrendTab(resourceId);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_main, null);
        unread_msg_number = (TextView) v.findViewById(R.id.unread_msg_number);
        initView(v);
        EventBus.getDefault().register(this);
        selectFragment(TAB_MAP);
        return v;
    }

    public void onEventMainThread(ReceiveMessageEvent event) {
        Log.d("NewMessage", "OnEvent收到了消息：" + event.getMsg());
        refreshUIWithMessage();
    }

    public void onEventMainThread(ConversationMessageHasReadEvent event) {
        Log.d("ClickConversation", "OnEvent收到了消息：" + event.getMsg());
        refreshUIWithMessage();
    }

    public void onEventMainThread(AddFriendEvent event) {
        Log.d("ReceiveMessage", "OnEvent收到了好友消息：" + event.fromUserId);
        refreshUIWithMessage();
    }

    public void onEventMainThread(AcceptFriendEvent event) {
        Log.d("ReceiveMessage", "OnEvent收到了好友消息：" + event.fromUserId);
        refreshUIWithMessage();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        // remove the unreadmessagelabel;
        refreshUIWithMessage();
        super.onResume();
    }
    /**
     * 初始化组件
     */
    private void initView(View view) {
        mTabs = new ImgTextBtn[TAB_COUNT];
        mTabs[TAB_MAP] = (ImgTextBtn) view.findViewById(R.id.btn_friend_main_map);
        mTabs[TAB_DISCOVER] = (ImgTextBtn) view.findViewById(R.id.btn_friend_main_discover);
        mTabs[TAB_FRIEND] = (ImgTextBtn) view.findViewById(R.id.btn_friend_main_friend);
//        mTabs[TAB_MEDIA] = (ImgTextBtn) view.findViewById(R.id.btn_friend_main_tingterest);
        mTabs[TAB_ME] = (ImgTextBtn) view.findViewById(R.id.btn_friend_main_me);
        mTabs[TAB_MAP].setSelected(true);
        TabButtonClickListener myTabButtonClickListener = new TabButtonClickListener();
        mTabs[TAB_MAP].setOnClickListener(myTabButtonClickListener);
        mTabs[TAB_ME].setOnClickListener(myTabButtonClickListener);
        mTabs[TAB_DISCOVER].setOnClickListener(myTabButtonClickListener);
        mTabs[TAB_FRIEND].setOnClickListener(myTabButtonClickListener);
//        mTabs[TAB_MEDIA].setOnClickListener(myTabButtonClickListener);

    }

    private void refreshUIWithMessage() {
        // 刷新bottom bar消息未读数
        updateUnreadLabel();
        if (currentTabIndex == TAB_FRIEND) {
            // 当前页面如果为聊天历史页面，刷新此页面
            mFriendFragment.refresh();
            mFriendFragment.refreshInviteMessage();
        }
    }

    /**
     * 刷新未读消息数
     */
    public void updateUnreadLabel() {
        int count = MessageUtils.getUnreadMsgCountTotal();
        if (count > 0) {
            unread_msg_number.setText(String.valueOf(count));
            unread_msg_number.setVisibility(View.VISIBLE);
        } else {
            unread_msg_number.setVisibility(View.INVISIBLE);
        }
    }

    private class TabButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            int index = -1;
            switch (view.getId()) {
                case R.id.btn_friend_main_map:
                    index = TAB_MAP;
                    break;
                case R.id.btn_friend_main_discover:
                    index = TAB_DISCOVER;
                    break;
                case R.id.btn_friend_main_friend:
                    index = TAB_FRIEND;
                    break;
//                case R.id.btn_friend_main_tingterest:
//                    index = TAB_MEDIA;
//                    break;
                case R.id.btn_friend_main_me:
                    index = TAB_ME;
                    break;
                default:
                    break;
            }
            selectFragment(index);
            selectTab(index);

            // TODO: 2016/2/14 should not refreshUnreadFriendInviteMessage here
            if (index == TAB_FRIEND) {
                if (MessageUtils.getUnreadMsgCountTotal() != 0) {
                    if (mFriendFragment != null) {
                        mFriendFragment.refresh();
                    }
                }
            }
        }
    }

    private void selectTab(int index) {
        for (ImgTextBtn btn: mTabs
             ) {
            btn.setSelected(false);
        }
        mTabs[index].setSelected(true);
    }

    /*
     * tab fragment
     */
    private Fragment selectFragment(int index) {
        if (currentTabIndex == index || index < 0 || index >= TAB_COUNT) {
            return mCurrentFragment;
        }

        // change the fragment
        FragmentTransaction ftx = getChildFragmentManager().beginTransaction();
        Fragment lastFragment = getFragment(currentTabIndex);
        if (lastFragment != null) {
            ftx = ftx.hide(lastFragment);
        }
        Fragment currentFragment = getFragment(currentTabIndex = index);
        if (!currentFragment.isAdded()) {
            ftx = ftx.add(R.id.fragment_main_container, currentFragment, String.valueOf(index));
        }
        ftx.show(currentFragment).commit();
        return currentFragment;

    }

    private Fragment getFragment(int index) {
        Fragment fragment = null;
        switch (index) {
            case TAB_MAP:
                if (mMapFragment == null) {
                    mMapFragment = new MapSpeedDashboardFragment();
                }
                fragment = mMapFragment;
                break;
            case TAB_DISCOVER:
                if (mDiscoveryFragment == null) {
                    mDiscoveryFragment = new DiscoveryFragment();
                }
                fragment = mDiscoveryFragment;
                break;
            case TAB_FRIEND:
                if (mFriendFragment == null) {
                    mFriendFragment = new FriendFragment();
                }
                fragment = mFriendFragment;
                break;
//            case TAB_MEDIA:
//                if (mMediaFragment == null) {
//                    mMediaFragment = new FragmentRecommends();
//                }
//                fragment = mMediaFragment;
//                break;
            case TAB_ME:
//                if (mUserFragment == null) {
//                    Account account = new Account();
//                    account.mAccountId = AccountUtils.getAccountID();
//                    account.mAvatar = AccountUtils.getAvatar();
//                    account.mNickName = AccountUtils.getNickName();
//                    mUserFragment = UserFragment.newInstance(account);
//                }
//                fragment = mUserFragment;
                if (mMineFragment == null){
                    mMineFragment = new MineFragment();
                }
                fragment = mMineFragment;
                break;
        }
        mCurrentFragment = fragment;
        return fragment;

    }
}
